/**
 * 
 */
package org.vsg.common.web.dom;

import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.PrettyXmlSerializer;
import org.htmlcleaner.TagNode;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Bill vison
 *
 */
public class HttpCleanerHttpServletRequestRefactor implements
		HttpServletRequestSourceRefactor, InitializingBean {

	@Autowired
	private HtmlCleanerHttpServletRequestProcessor processor;

	@Autowired(required = false)
	private CleanerProperties properties;	

	private HtmlCleaner cleaner;	
	
	/* (non-Javadoc)
	 * @see org.vsg.common.web.dom.HttpServletRequestSourceRefactor#refact(javax.servlet.http.HttpServletRequest, java.io.InputStream)
	 */
	@Override
	public String refact(HttpServletRequest request, InputStream in)
			throws IOException {
		// TODO Auto-generated method stub
		TagNode node = cleaner.clean( in );
		
		TagNode resultNode = processor.process( request , node);
		
		PrettyXmlSerializer xmlSeri = new PrettyXmlSerializer( cleaner.getProperties() );
		
		CharArrayWriter output = new CharArrayWriter();
		
		xmlSeri.writeXml(resultNode, output , "UTF-8" );
		
		return new String(output.toCharArray());
	}

	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		if (properties == null) {
			cleaner = new HtmlCleaner();
		}
		else {
			cleaner = new HtmlCleaner(properties);
		}
		
	}

}
